package com.lishangshan.oas_system.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Configuration
public class StringtoDateUtil implements Converter<String, Date> {

    static SimpleDateFormat sdf = new SimpleDateFormat();
    private static List<String> patterns = new ArrayList<>();

    static {
        patterns.add("yyyy-MM-dd HH:mm:ss");
        patterns.add("yyyy-MM-dd HH:mm");
        patterns.add("yyyy-MM-dd");
        patterns.add("HH:mm");
        patterns.add("yyyy-MM");
    }

    /**
     * STRING TO DATE  字符串转日期
     *
     * @param source
     * @return
     */
    @Override
    public Date convert(String source) {
        Date date = null;
        for (String p : patterns) {
            try {
                sdf.applyPattern(p);
                date = sdf.parse(source);
                break;
            } catch (ParseException e) {
            }
        }
        if (date == null) {
            throw new IllegalArgumentException("日期格式错误！[" + source + "]");
        }
        return date;
    }


    public void setPatterns(List<String> patterns) {
        this.patterns = patterns;
    }

    /**
     * DATE TO STRING 日期 转字符
     *
     * @param date
     * @return
     */
    public static String stringToDate(Date date) {
        String str = null;
        for (String p : patterns) {
            try {
                sdf.applyPattern(p);
                str = sdf.format(date);
                break;
            } catch (Exception e) {
                System.out.println("打印 异常");
                e.printStackTrace();
            }
        }
        if (str == null) {
            throw new IllegalArgumentException("字符串格式错误！[" + str + "]");
        }
        return str;
    }

    /**
     * 获取 当前  年月 日  不包含时分秒
     *
     * @return
     */
    public static String newDateNYR() {
        Date d = new Date();
        System.out.println(d);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String newDateNYR = sdf.format(d);
        System.out.println("格式化后的日期：" + newDateNYR);
        return newDateNYR;
    }
}
